package com.erp.erp_servers.Ftp.imp;

import com.erp.erp_servers.Ftp.IFtpService;
import com.erp.utils.FtpUtils;
import com.erp.utils.OSUtils;
import com.erp.utils.UploadFile;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName ImpFtpService
 * @Description TODO
 * @Author songjizhen
 * @Date 2020-07-04 23:01
 * @Version 1.0
 */
@Service
public class ImpFtpService  implements IFtpService {
    private static String ALLPATH="/data0/AllPath";
    static {
        if(OSUtils.isOSLinux()){
            ALLPATH="/data0/AllPath";
        }
        if(OSUtils.isOSWin()){
            ALLPATH=OSUtils.getHome();
            ALLPATH=ALLPATH.substring(0,ALLPATH.length()-1);
            ALLPATH= ALLPATH.replaceAll("\\\\","/");
        }
        System.out.println("ALLPATH"+ALLPATH);
    }
    /**
     * @param request
     * @param fileType
     * @param ftppath
     * @return
     */
    @Override
    public List<UploadFile> upload(MultipartHttpServletRequest request, String fileType,String ftppath) throws IOException {
        MultiValueMap<String, MultipartFile> map = request.getMultiFileMap();// 为了获取文件，这个类是必须的
        List<MultipartFile> list = map.get("uploadify");// 获取到文件的列表
        List<UploadFile> filenameList = new ArrayList();//
        FtpUtils ftp = null;
        UploadFile uploadFile = null;
        // 遍历文件列表
        for (MultipartFile mFile : list) {
            String originalFileName = mFile.getOriginalFilename();//获取文件名称(绝对路径)
            FileInputStream inputStream = (FileInputStream) mFile.getInputStream();
            String fileName = this.getFileName(originalFileName);//mFile.getName();//
            uploadFile = new UploadFile();
            uploadFile.setOriginalFileName(fileName);
            //文件重命名
            fileName=changename(fileName);
            ftp = new FtpUtils();
            String romotePath = ftppath + "/" + fileType;
            boolean b = ftp.uploadFile(romotePath, fileName, inputStream);
            uploadFile.setFileName(fileName);
            uploadFile.setStatus(b);
            // uploadFile.setFtpPath(romotePath + "/" + this.getFileName(originalFileName));
            uploadFile.setFtpPath(romotePath );
            filenameList.add(uploadFile);
        }
        return filenameList;
    }

    @Override
    public void ftpUpload(String ftppath) throws IOException {
        //    ftppath=   ftp/downloadimg?pathname=/data0/AllPath     /upload/4/admin/1617800647623/seal   &filename=  1617800647623.gif
        //    ftppath=   ftp/downloadimg?pathname=   /data0/AllPath/upload/4/admin/1617800647623/seal&filename=1617800647623.gif
        FtpUtils ftp=new FtpUtils();
        String s = ftppath.split("/data0/AllPath")[1];
        String romote=s.split("&filename=")[0];
        String romotePath=romote.substring(7,romote.length());
        String fileName=s.split("&filename=")[1];
        String s1 = ftppath.split("pathname=")[1];
        String input=s1.split("&filename=")[0]+"/"+s1.split("&filename=")[1];
        InputStream inputStream =new FileInputStream(input);
        boolean b = ftp.ftpUpload(romotePath, fileName, inputStream);

    }

    private String changename(String filename){
       // return filename;
        String  obs=filename.substring(filename.lastIndexOf("."));
        String tempUUID = UUID.randomUUID().toString().replace("-", "");
       return tempUUID+System.currentTimeMillis()+obs;
    }
    /**
     * 下载文件 *
     *
     * @param pathname  FTP服务器文件目录 *
     * @param filename  文件名称 *
     * @param localpath 下载后的文件路径 *
     * @return
     */
    @Override
    public boolean downloadFile(String pathname, String filename, String localpath) {
        FtpUtils ftp = new FtpUtils();
        boolean b = ftp.downloadFile(pathname, filename, localpath);
        return b;
    }

    /**
     * 图片输入到页面，用于展示
     *
     * @param path
     * @param fileName
     * @returndownloadFile
     */
    @Override
    public void download(String path, String fileName, HttpServletResponse response)  {
        InputStream in = null;
        String fen = System.getProperty("file.separator");
        try{
            //从minio文件服务器上获取图片流
//            in = zipUnit.zipOut(path + fen + fileName);
            in = new FileInputStream(new File(path+fen+fileName));
            response.setContentType("image/png");
            OutputStream out = response.getOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = in.read(buff, 0, 100)) > 0) {
                out.write(buff, 0, rc);
            }
            out.flush();
        } catch (Exception e) {
//            return ResponseResult.success();
        }finally {
            try {
                if (null != in) {
                    in.close();
                }
            }catch (Exception e){

            }
        }
//        OutputStream out=null;
//        //获取FTPClient
//        FtpUtils ftpUtils=new FtpUtils();
//        ftpUtils.initFtpClient();
//        FTPClient ftp=ftpUtils.ftpClient;
//        try {
//            out = response.getOutputStream();
//            //切换工作目录
//            boolean change = ftp.changeWorkingDirectory(path);
//            //OutputStream outputStream=null;
//            //被动模式
//            ftp.enterLocalPassiveMode();
//            //设置文件 2进制传输
//            ftp.setFileType(ftp.BINARY_FILE_TYPE);
//
//            //ftp缓存(1)
//            ftp.setBufferSize(1024*1024);
//            if(change){
//                FTPFile[] fs = ftp.listFiles();
//                for (int i = 0; i < fs.length; i++) {
//                    FTPFile ff = fs[i];
//                    if (ff.getName().equals(fileName)) {
//                        ftp.retrieveFile(fileName,out);
//                        break;
//                    }
//                }
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }finally {
//            try {
//                out.close();
//                if(ftp.completePendingCommand()){
//                    ftp.logout();
//                    ftp.disconnect();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//        }



    }

    /**
     * 获取文件名称
     * @param filePathName
     * @return
     */
    private String getFileName(String filePathName){
        String[] strs=filePathName.split("\\\\");
        return strs[strs.length-1];
    }
    /**
     * 上传邮件附件
     * @param pathname 存储相对路径
     * @param fileName 附件名字
     * @param inputStream 附件的流
     * @return
     */
    @Override
    public String uploadEmailAdjunct(String pathname, String fileName, InputStream inputStream) throws IOException {
        FtpUtils ftp=new FtpUtils();
        ftp.uploadFile(ALLPATH+pathname, fileName, inputStream);
        String upPath="ftp/downloadimg?pathname="+ALLPATH+pathname+"&filename="+fileName;
        return upPath;
    }

    @Override
    public File downLoadFile(String pathname, String fileName) {
        FtpUtils ftp = new FtpUtils();
        return null;}
}
